﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Casamiel.Domain;
using Casamiel.Domain.Request;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class GetDayProductDetailCommandHandler : BaseCommandHandler, IRequestHandler<GetDayProductDetailCommand, BaseResult<GoodsProductBaseRsp>>
    {
        private readonly IMbrStoreRepository _mbrStore;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="storeRepository"></param>
        /// <param name="netICService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="settings"></param>
        public GetDayProductDetailCommandHandler(IMbrStoreRepository storeRepository, INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
        {
            _mbrStore = storeRepository;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<BaseResult<GoodsProductBaseRsp>> Handle(GetDayProductDetailCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var storeinfo = await _mbrStore.GetByStoreIdAsync<ICasaMielSession>(request.Storeid).ConfigureAwait(false);
            if (storeinfo == null)
            {
                return new BaseResult<GoodsProductBaseRsp>(null, 999, "storeid 有误");
            }
            var url = "CakeMall/v1/Goods/GetById";
            var data = new { storeId = request.Storeid, productId = request.Productid };
            var rsp = await PostThirdApiAsync<GoodsProductBaseRsp>(url, JsonConvert.SerializeObject(data)).ConfigureAwait(false);
            // var rsp = JsonConvert.DeserializeObject<JObject>(result);
            //if (rsp["resultNo"].ToString() != "00000000")
            //{
            //    return new BaseResult<Goods_ProductBaseRsp>(null, 9999, rsp["resultRemark"].ToString());
            //}
            if (rsp.Code > 0)
            {
                return rsp;
            }
            // var entity = JsonConvert.DeserializeObject<Goods_ProductBaseRsp>(rsp["data"].ToString());

            var req = new ProductStockQueryReq();

            if (rsp.Content != null)
            {
                req.product = new List<ProductStockReq>();
                foreach (var item in rsp.Content.GoodsList)
                {
                    req.product.Add(new ProductStockReq { pid = $"{item.RelationId}" });

                }

                req.shopid = rsp.Content.StoreRelationId;

                var zmodel = await NetICService.Productstockquery(req).ConfigureAwait(false);
                //var zmodel = await _icApiService.icprice(dto);
                if (zmodel != null)
                {
                    var _count = rsp.Content.GoodsList.Count;
                    for (int i = 0; i < _count; i++)
                    {
                        var t = zmodel.product.Find(a => a.pid == $"{rsp.Content.GoodsList[i].RelationId}");
                        if (t != null && t.icprice > 0)
                        {
                            rsp.Content.GoodsList[i].Status = 1;
                            rsp.Content.GoodsList[i].Price = t.originprice;
                            rsp.Content.GoodsList[i].CostPrice = t.icprice;
                            if (storeinfo.IsLimitStock == 1)
                            {
                                rsp.Content.GoodsList[i].StockQuentity = 100;
                            }
                            else
                            {
                                rsp.Content.GoodsList[i].StockQuentity = t.count;
                                if (t.count <= 0)
                                {
                                    rsp.Content.GoodsList[i].Status = 0;
                                }
                            }
                        }
                    }
                    //foreach (var item in rsp.Content.GoodsList)
                    //{
                    //    var t = zmodel.product.Find(a => a.pid == item.RelationId.ToString());
                    //    if (t != null && t.icprice > 0)
                    //    {
                    //        item.Status = 1;
                    //        item.Price = t.originprice;
                    //        item.CostPrice = t.icprice;
                    //        if (storeinfo.IsLimitStock == 1)
                    //        {
                    //            item.StockQuentity = 100;
                    //        }
                    //        else
                    //        {

                    //            item.StockQuentity = t.count;
                    //            if (t.count <= 0)
                    //            {
                    //                item.Status = 0;
                    //            }
                    //        }
                    //    }
                    //}
                }
                else
                {
                    return new BaseResult<GoodsProductBaseRsp>(null, 9999, "库存不足");
                }
            }
            return rsp;
        }
    }
}
